import { PageContainer } from '@ant-design/pro-layout';
import { message,Col,Row,Drawer, Spin, Upload, Modal, Popconfirm} from 'antd';
import ProTable, { ActionType, EditableProTable } from '@ant-design/pro-table';
import React, { useEffect, useState} from 'react';
import type { ProColumns } from '@ant-design/pro-table';
import request from '@/utils/request';
import UpDownLabel from '@/components/Common/UpDownLabel';
import { useRef } from 'react';
import { Button } from 'antd';
import {exportFile} from '@/utils/utils';
import ProForm, { DrawerForm, ProFormDatePicker, ProFormDigit, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import { InputNumber } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import {newUUID,moneyFormat,momentNow} from '@/utils/utils';
import {putOutFormListNoBill,getPutOutDetail,billList,saveBill,updateBill,billDelById,authorizationData} from '../../pages/StockIO/service';
import { history } from 'umi';

const { confirm } = Modal;
export type PutOutProps = {
    dealer:boolean;
};

const DealerTicket: React.FC<PutOutProps> = (props)=>{
  const [spinningFlag,setSpinningFlag] = useState(false);
  const [currentRecord,setCurrentRecord] = useState<any>({});
  const [showDetail, setShowDetail] = useState(false);
  const [previewVisible,setPreviewVisible] =  useState(false);
  const [previewImage,setPreviewImage] =  useState('');
  const actionRef = useRef<ActionType>();
  const [showTicket,setShowTicket] = useState(false);
  const [chooseOut,setChooseOut] = useState(false);
  const [editFlag,setEditFlag] =  useState(false);
  const [ticketProData,setTicketProData] = useState<any>([]);
  const [fileList,setFileList] = useState<any>([]);
  const [shipId,setShipId] = useState('');
  const [pIndex,setPindex] = useState(0);
  const [editableKeys, setEditableRowKeys] = useState<any>({});
  const [expandedRowKeys,setExpandedRowKeys] = useState<any>([1]);
  const [recvList,setRecvList] = useState<any[]>([]);
  const [hosList,setHosList] = useState<any[]>([]);
  const [hosHideFlag,setHosHideFlag] =  useState(true);
  const [recv,setRecv] = useState<any>({});

  function deleteBill(params:any) {
    var data =  request('/xwyl/bill/deleteBill', {
      method: 'POST',
      params,
    });
    return data;
  }

  function exportTicket(params:any){
    var data =  request('/xwyl/bill/exportBillInfo', {
      method: 'POST',
      params,
    });
    return data;
  }
  
  

  function billDataById(params:any) {
    var data =  request('/xwyl/bill/billDataById', {
      params,
    });
    return data;
  }

  //表头信息以及表值设置
  const dealerColumn: ProColumns[] = [
    {
      title:'客户代码',
      dataIndex: 'dealerCode',
      width:100
    },
    {
      title:'客户名称',
      width:200,
      ellipsis:true,
      dataIndex: 'dealerName',
    },
  ];


  useEffect(()=>{
    if(props.dealer){
      initRecv();
    }
    return function cleanup() {  
    };
    },[]);

  async function initRecv(){
    var val=await authorizationData({});
    if(val.errorCode==='200'){
      var customer:any[]=[];
      var dealer:any[]=[];
      val.data.customer.forEach((element:any) => {
        customer.push({'label':element.customerName,'value':element.customerId,'type':element.category});
      });
      val.data.authorization.forEach((element:any) => {
        dealer.push({'label':element.child_dealerName,'value':element.child_dealerId});
      });

      setHosList(val.data.customer.filter((ele:any)=>{
        return ele.category==='1'
      }).map((item:any)=>{
        return {'label':item.customerName,'value':item.customerId}
      }))
      setRecvList(customer);
    }
 }

  const baseColumn:ProColumns[]=[
  {
    title:'发票代码',
    dataIndex: 'bill_code',
    width:150,
    hideInSearch:true
  },
  {
    title: '发票号码',
    width:100,
    dataIndex: 'bill_number',
  },
  {
    title: '提交日期',
    dataIndex: 'createDate',
    width:100,
    hideInSearch:true,
  },
  {
    title:'发票日期',
    valueType:'dateRange',
    dataIndex: 'date',
    width:100,
    hideInTable:true,
  },
  {
    title: '发票日期',
    dataIndex: 'bill_date',
    width:100,
    hideInSearch:true,
  },
  {
    title: '购买方',
    dataIndex: 'customer',
    width:200,
    ellipsis:true,
  },
  // {
  //   title: '税率',
  //   dataIndex: 'rate',
  //   hideInSearch:true,
  // },
  {
    title: '不含税总金额',
    dataIndex: 'taxAmount',
    valueType:'money',
    width:100,
    hideInSearch:true,
  },
  {
    title: '操作',
    valueType: 'option',
    width:120,
    render: (text, record:any,_, action) => [
      <a
      key='detail'
      onClick={async() => {
        setSpinningFlag(true);
        var val = await billDataById({'id':record.id});
        if(val.errorCode==='200'){
          val.data.attList.forEach((element:any) => {
            element.name = element.attName;
            element.url = element.attPath;
            element.uid = element.id;
          });
          setCurrentRecord(val.data);
          setRecv({label:val.data.bill.customer,value:val.data.bill.customerId});
          setHosHideFlag(true)
          for(var i=0;i<recvList.length;i++){
            if(recvList[i].type==='2'&&recvList[i].value ===val.data.bill.customerId ){
              setHosHideFlag(false)
              break;
            }
          }

          setFileList(val.data.attList)
          var temIndex = pIndex;
          var keys = {};
          val.data.product.forEach((element:any) => {
            element.exist = true;
            element.list.forEach((item:any)=>{
              item.pIndex=temIndex
              item.num = item.numbs;
              item.stand = item.standard_price;
              temIndex++;
              element.id = item.putout_id
            })
            keys[element.id] = element.list.map((item:any)=>item.pIndex)
          });
          setShipId(record.id);
          setPindex(temIndex)
          setTicketProData(val.data.product)
          setExpandedRowKeys(val.data.product.map((item:any)=>item.id))
          setEditableRowKeys(keys)
          setShowDetail(true);
        }else{
          message.error('获取详情失败');
        }
        setSpinningFlag(false);
      }}
    >
      详情
    </a>,
       props.dealer? <Popconfirm  title='确定删除该发票吗?'  key='delete' onConfirm={async() => {
          var val = await deleteBill({'ids':record.id});
          if(val.errorCode==='200'){
            message.success('删除成功')
            actionRef.current?.reloadAndRest?.();
          }else{
            message.error(val.errorMessage);
          }
      }}>
        <a hidden={sessionStorage.getItem('access')==='analysis'}>删除</a>
        </Popconfirm>:<a key='empty'></a>,
      <a key='edit' hidden={sessionStorage.getItem('access')==='analysis'} onClick={async()=>{
        setSpinningFlag(true);
        var val = await billDataById({'id':record.id});
        if(val.errorCode==='200'){
          setCurrentRecord(val.data);
          setEditFlag(true);
          setShipId(record.id)
          val.data.attList.forEach((element:any) => {
            element.name = element.attName;
            element.url = element.attPath;
            element.uid = element.id;
          });
          setFileList(val.data.attList)
          setRecv({label:val.data.bill.customer,value:val.data.bill.customerId});
          setHosHideFlag(true)
          for(var i=0;i<recvList.length;i++){
            if(recvList[i].type==='2'&&recvList[i].value ===val.data.bill.customerId ){
              setHosHideFlag(false)
              break;
            }
          }
        }
        setSpinningFlag(false);
      }}>修改</a>
    ]
  }
  ]

  const outColumn : ProColumns[] = [
    {
      title:'出库单号',
      dataIndex: 'putOutNo',
    },
    {
      title: '收货方',
      dataIndex: 'receiver',
      initialValue:recv.label,
    },
    {
      title: '提交日期',
      dataIndex: 'createDate',
      hideInSearch:true,
    },
    {
        title: '出库日期',
        dataIndex: 'putOutDate',
        hideInSearch:true,
    },
    {
      title: '出库日期',
      dataIndex: 'date',
      valueType:'dateRange',
      hideInTable:true,
    },
    // {
    //   title: '出库金额',
    //   dataIndex: 'salesAmount',
    //   valueType:'money',
    //   hideInSearch:true
    // },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record:any,_, action) => [
       <a hidden={!props.dealer}
       key='ticket'
       onClick={async() => {
          //构造下产品
          if(record.isBack==1){
            message.warning('该出库单已被撤销');
            return;
          }
          var val = await getPutOutDetail({'putOutId':record.id});
          if(val.errorCode==='200'){
              for(var i=0;i<ticketProData.length;i++){
                if(ticketProData[i].id==record.id){
                    message.warning('已选择该出库单');
                    return;
                }
              }
              var currrentPos = pIndex;
              for(var i=0;i<val.data.Product.length;i++){
                if(val.data.Product[i].reason_type&&val.data.Product[i].reason_type!='5'){
                  message.warning('该出库单已设置为不开票');
                  return;
                }
                val.data.Product[i].pIndex = currrentPos;
                val.data.Product[i].num = 1;
                val.data.Product[i].out_numbs = val.data.Product[i].numbs;
                currrentPos++;
              }
              setPindex(currrentPos);
              var list = val.data.Product.filter((item:any)=>{
                if(!item.invoicing){
                  return true;
                }
                return  Number(item.invoicing)!=item.numbs;
              })
              if(list.length==0){
                message.warning('该出库单产品已全部开票');
                return;
              }
              record.list = list;
              record.exist = false;
              var arrayData =[...ticketProData,record]
              console.log(arrayData)
              setTicketProData(arrayData)
              setExpandedRowKeys(arrayData.map((item)=>item.id))
              var keys = {...editableKeys};
              keys[record.id] = record.list.map((item:any)=>item.pIndex)
              setEditableRowKeys(keys)
              setChooseOut(false)
          }else{
            message.error('获取出库单失败');
          }
      }}
       >选择
       </a> 
     ]
    }
  ]

  const outColumn2 : ProColumns[] = [
    {
      title:'出库单号',
      dataIndex: 'putOutNo',
    },
    {
      title: '收货方',
      dataIndex: 'receiver',
    },
    {
      title: '提交日期',
      dataIndex: 'createDate',
      hideInSearch:true,
    },
    {
      title: '出库日期',
      dataIndex: 'putOutDate',
      hideInSearch:true,
    },
    // {
    //   title: '出库金额',
    //   dataIndex: 'salesAmount',
    //   valueType:'money',
    //   hideInSearch:true,
    // },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record:any,_, action) => [
        <Popconfirm  title='确定删除该出库单吗?'  key='delete' onConfirm={async() => {
          if(ticketProData.length==1){
            message.warning('请先选择新的出库单，再删除')
            return;
          }
          if(record.exist){
            var val = await billDelById({putout_id:record.id,bill_id:shipId});
            if(val.errorCode==='200'){
              var list = [...ticketProData];
              list = list.filter((item)=>{
                  return item.id!=record.id;
              });
              setExpandedRowKeys(list.map((item)=>item.id))
              setTicketProData(list);
            }else{
              message.error(val.errorMessage)
            }
          }else{
            var list = [...ticketProData];
            list = list.filter((item)=>{
                return item.id!=record.id;
            });
            setExpandedRowKeys(list.map((item)=>item.id))
            setTicketProData(list);
          }
      }}>
       <a hidden={!props.dealer}
       key='ticket'
       >删除
       </a> </Popconfirm>
     ]
    }
  ]

  const uploadProps = {
    multiple: false,
    name: 'file',
    accept:'image/*,application/pdf',
    action: '/xwyl/attachment/uploadAttach',
    headers: {
      authorization: 'authorization-text',
    },
    beforeUpload:(file: any, FileList: any[])=>{
      var flag =  file.type.indexOf('image/')>=0||file.type.indexOf('pdf')>=0;
      if(!flag){
         message.error('请上传图片格式或pdf格式')
      }
      return flag;
    }
  };


  const limitDecimalsP =(value:any)=>{
    let reg = /^(-)*(\d+)\.(\d\d).*$/;
    return value.replace(/￥\s?|(,*)/g, '').replace(reg,'$1$2.$3');
  };


  const limitDecimalsF =(value:any)=>{
    let reg = /^(-)*(\d+)\.(\d\d).*$/;
    return `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',').replace(reg,'$1$2.$3');
  };

  const expandedRowRender=(val:any)=>{
    const columns:any = [
      { title: '产品名称', dataIndex: 'product_name', editable: false},
      { title: '产品型号', dataIndex: 'product_standard', editable: false},
      { title: '批号', dataIndex: 'batch', editable: false},
      { title: '出库数量', dataIndex: 'out_numbs', editable:false},
      { title: '开票数量', dataIndex: 'num', editable:true,
        formItemProps: (form, { rowIndex }) => {
          return {
            rules: [{ required: true, message: '开票数量必填'}]
          };
        },
        renderFormItem: (_, { type, defaultRender, formItemProps, fieldProps,record, ...rest }, form:any) => {
          return <InputNumber {...fieldProps} readOnly={!props.dealer} placeholder='请输入'  precision={0} min={0}/>;
        },
      },
      { title: '开票单价(不含税)', dataIndex: 'stand',  editable:true,valueType:'money',
        formItemProps: (form, { rowIndex }) => {
          return {
            rules: [{ required: true, message: '开票单价必填'}]
          };
        },
        renderFormItem: (_, { type, defaultRender, formItemProps, fieldProps, ...rest }, form) => {
          return <InputNumber  style={{
            width: 150,
          }} {...fieldProps} readOnly={!props.dealer}  placeholder='请输入' step={0.01} 
           min={0}/>;
        },
      },
      { title: '开票金额(不含税)', dataIndex: 'total', valueType:'money',editable: false,renderText:(_:string,record:any)=>{
          if(record.stand&&record.num){
            return record.stand*record.num
          }
          return 0;
      }},
    ];
    const data =val.list;
    return <EditableProTable columns={columns} value={data} rowKey='pIndex' toolBarRender={false}
       pagination={false} size='small'
      search={false} toolbar={[]} locale={{emptyText:'暂无'}}
      recordCreatorProps={false}
      onChange={(data) => {     
          console.log(data)  
      }}
      editable={{
        editableKeys:editableKeys[val.id],
        type: 'multiple',
        onValuesChange: (record, recordList) => {
            val.list=recordList;
            setTicketProData([...ticketProData])
          }
      }}
    />;
  }

  
  const handlePreview=async(file:any)=>{
    if(file.url){
        setPreviewImage(file.url);
    }else{
        setPreviewImage(file.attPath);
    }
    setPreviewVisible(true);
  };

  function onChange(value:any,val:any) {
    if(val.type==='2'){
      setHosHideFlag(false)
    }else{
      setHosHideFlag(true)
    }
    setRecv(val);
  }

  function disabledDate(current:any) {
    return current && current > momentNow().endOf('day');
  }

  function  formatType(t:string) {
    if(t==='1'){
      return '一级客户(在直接订货的)'
    }
    if(t==='2'){
      return '二级客户(从一级客户拿货的)'
    }
    if(t==='3'){
      return '托管公司'
    }
    if(t==='4'){
      return '私立医院'
    }
    return '配送公司'
  }

  var thisColumn = props.dealer?baseColumn:[...dealerColumn,...baseColumn]

  return (
    <PageContainer>
    <div style={{color:'red',marginBottom:10}}>温馨提示：<br/>1:无法开票时请点击未开票,到出库单中填写未开票原因</div>

    <ProTable
      headerTitle=''
      actionRef={actionRef}
      scroll={{x:1500}}
      request={(params, sorter, filter) => {
        if(params.date){
          params.beginDate=params.date[0];
          params.endDate=params.date[1];
          params.date=undefined;
        }
        params.types = 1;
        return billList({...params,filter})
       }}
      columns={thisColumn}
      rowKey='id'
      pagination={{
        pageSizeOptions:['20', '100', '500']
      }}
      search={{span:6,
      collapseRender:false,
      optionRender: ({ searchText, resetText }, { form }) => [
            <Button
              key='search'
              type='primary'
              onClick={() => {
                form?.submit();
              }}
            >
              {searchText}
            </Button>,
            <Button
              key='rest'
              onClick={() => {
                form?.resetFields();
                form?.submit();
              }}
            >
              {resetText}
            </Button>,
            <Button key='out' hidden={props.dealer} onClick={async()=>{
              setSpinningFlag(true);
              var date = form?.getFieldValue('date');
              var params:any={};
              if(date){
                params.beginDate=date[0].format('YYYY-MM-DD');
                params.endDate=date[1].format('YYYY-MM-DD');
                params.date=undefined;
              }
            
              params.dealerName= form?.getFieldValue('dealerName');
              params.bill_number= form?.getFieldValue('bill_number');
             
              var val = await exportTicket(params);
              if(val.errorCode==='200'){
                exportFile(val.data,'发票.xlsx')
              }else{
                message.error(val.errorMessage);
              }
              setSpinningFlag(false);
            }}>导出</Button>,
          ],
        
      }}
      toolbar={{settings:[]}}
      editable={{
        type: 'multiple',
        onSave: async (values:any,record) => {
        },
        onDelete:async (value:any)=>{
        }
      }}
      toolBarRender={() => [
        <Button
          hidden={!props.dealer}
          type='primary'
          key='primary'
          onClick={() => {
            setShipId(newUUID());
            setTicketProData([]);
            setRecv({})
            setFileList([]);
            setShowTicket(true);
          }}
        >
          新增发票
        </Button>
        ,<Button  hidden={!props.dealer}
        type='primary' key='no' onClick={()=>{
          history.push('/stockIO/outList');
          }}>未开票</Button>
      ]}
      />

         <DrawerForm
           title='详情'
           width={1300}
           submitter={{
            render: (_, defaultDoms) => {
              return props.dealer?defaultDoms:[];
            },
          }}
           visible={showDetail}
           onVisibleChange={(v)=>{
             setShowDetail(v);
           }}
           drawerProps={{
             forceRender: true,
             destroyOnClose: true,
           }}
           onFinish={async (values: any) => {
               if(fileList.length==0){
                  message.warning('请上传发票照片')
                  return false;
                }
                values.shipId = shipId;
                values.bill_type = '普票'
                values.types = 1
                values.isUpdate=1
                // if(values.hospital){
                // values.hospital_id=currentRecord?.bill?.customerId
                // }else{
                // values.customerId=currentRecord?.bill?.customerId
                // }
                // values.customer = currentRecord?.bill?.customer
                var param:any={bill:values,product: []}
                for(var i=0;i<ticketProData.length;i++){
                    for(var j=0;j<ticketProData[i].list.length;j++){
                        var item = {...ticketProData[i].list[j]};
                        // if(item.num || !item.stand){
                        //   message.warning(请填写数量，金额)
                        //   return;
                        // }
                        if(item.num ==undefined){
                          item.num=0;
                        }
                        if(item.stand ==undefined){
                          item.stand=0;
                        }
                        item.standard_price=item.stand;
                        item.numbs = item.num;
                        item.putout_id = ticketProData[i].id;
                        param.product.push(item);
                    }
                }
                if(param.product.length==0){
                  message.warning('请点击选择出库单');
                  return false;
                }
                var val = await saveBill(param);
                if(val.errorCode==='200'){
                     message.success('提交成功')
                    actionRef.current?.reloadAndRest?.();
                    return true;
                }else{
                    message.error(val.errorMessage);
                    return  false;
                }
           }}>
           <Row >
            <Col span={6}><UpDownLabel title='发票代码' texts={[currentRecord.bill?.bill_code]}></UpDownLabel></Col>
              <Col span={6}><UpDownLabel title='发票号码' texts={[currentRecord.bill?.bill_number]}></UpDownLabel></Col>
              <Col span={6}><UpDownLabel title='发票日期' texts={[currentRecord.bill?.bill_date]}></UpDownLabel></Col>
              <Col span={6}><UpDownLabel title='不含税总金额' texts={[moneyFormat(currentRecord.bill?.taxAmount)]}></UpDownLabel></Col>
           </Row>
           <Row>
            <Col span={12}><UpDownLabel title='购买方' texts={[currentRecord.bill?.customer]}></UpDownLabel></Col>
            <Col span={12}><UpDownLabel title='销售方' texts={[currentRecord.bill?.dealerName]}></UpDownLabel></Col>

            <Col span={12}><UpDownLabel title='发票上开票公司名称' texts={[currentRecord.bill?.corporate_name]}></UpDownLabel></Col>
            <Col span={12}><UpDownLabel title='开票公司类型' texts={[formatType(currentRecord.bill?.company_type)]}></UpDownLabel></Col>
           </Row>
           <Row>
              <Col span={24}><UpDownLabel title='备注' texts={[currentRecord.bill?.bz]}></UpDownLabel></Col>
           </Row>
           <div style={{color:'red',margin:'20px 0'}}>
           如将产品销售给托管平台，上报植入需要附上产品使用证明，如：出库单、外壳包装、术中条形码等
           </div>
           <div key='tab1'>
                <Button key='chooseTicket' hidden={!props.dealer} type='primary' onClick={()=>{
                    setChooseOut(true);
                }}>选择出库单</Button>
              {ticketProData && ticketProData.length?
              <ProTable
                className='components-table-demo-nested'
                headerTitle='产品列表'
                size='small'
                toolbar={[]}
                columns={outColumn2}
                dataSource={ticketProData}
                rowKey='id'
                pagination={false}
                search={false}
                toolBarRender={false}
                expandable={{expandedRowRender,defaultExpandAllRows:true,expandIconColumnIndex:-1,expandedRowKeys}}
              />:<div key='em'></div>}
          </div>           
          <div key='up'><br></br><UpDownLabel title='发票附件' texts={[]}></UpDownLabel></div>
          <Upload  {...uploadProps} onPreview={handlePreview}  fileList={fileList}
                onRemove={(record)=>{
                  confirm({
                    content: '确定删除吗？',
                    onOk:async()=> {
                      if(fileList.length==1){
                        message.warning('请先上传新的附件，再删除')
                        return;
                      }
                      var req = request('/xwyl/attachment/deleteAtt', {
                        method: 'POST',
                        requestType:'form',
                        data: {
                          ...{id:record.uid},
                          method: 'post',
                        },
                      });
                      var val =await req;
                      if(val.errorCode==='200'){
                        var newList=fileList.filter((item:any)=>{
                          return item.uid!=record.uid;
                        });
                        setFileList(newList);
                      }else{
                        message.error('删除失败');
                      }
                    },
                    onCancel() {
                      console.log('Cancel');
                    },
                  });
                }}
                onChange={(info:any)=>{
                  if (info.file.status === 'done') {
                    if(info.file.response.errorCode==='200'){
                      var list:any[] = fileList;
                      message.success(`${info.file.name}上传成功`);
                      var data = info.file.response.data;
                      data.uid = data.attId;
                      data.name = info.file.name;
                      data.url = data.location;
                      data.status ='done';  
                      list.push(data);
                      setFileList([...list]);
                    }else{
                      message.error(`${info.file.name} 上传失败.`);
                    }
                  } else if (info.file.status === 'error') {
                    message.error(`${info.file.name} 上传失败.`);
                  }
                }}   data={{'shipId':shipId,'userId':sessionStorage.getItem('userId')}} headers={{
                  'authorization':`${sessionStorage.getItem('token')}`}}>
                <Button hidden={!props.dealer}  icon={<UploadOutlined />}><span style={{color:'red'}}>*</span>上传发票</Button>
              </Upload>
         </DrawerForm>
         <Modal
            visible={previewVisible}
            width={1000}
            footer={null}
            onCancel={()=>setPreviewVisible(false)}
           >
          <img style={{ width: '100%' }} src={previewImage} />
        </Modal>

        <DrawerForm
            width={1300}
            title='新增发票'
            visible={showTicket}
            submitter={{
              render: (props, defaultDoms) => {
                return [
                  <span style={{color:'#f10000'}}>请再次核对上报信息是否无误，以免商务部核查有问题需再次上报！</span>,
                  ...defaultDoms,
                ];
              },
            }}
            onVisibleChange={(v)=>{
              setShowTicket(v);
            }}
            drawerProps={{
              forceRender: true,
              destroyOnClose: true,
            }}
            onFinish={async (values: any) => {
                if(fileList.length==0){
                    message.warning('请上传发票照片')
                    return false;
                }
                if(values.bill_number.length!=8){
                  message.warning('发票号码必须为8位')
                  return false;
                }
                values.shipId = shipId;
                values.bill_type = '普票'
                values.types = 1
                values.isUpdate=0
                values.customer = recv.label
                values.customerId = recv.value
                if(values.hospital){
                  values.hospital_id=values.hospital
                }else{
                  values.hospital_id= ''
                }
                var param:any={bill:values,product: []}
                for(var i=0;i<ticketProData.length;i++){
                    for(var j=0;j<ticketProData[i].list.length;j++){
                        var item = {...ticketProData[i].list[j]};
                        if(item.num ==undefined){
                          item.num=0;
                        }
                        if(item.stand ==undefined){
                          item.stand=0;
                        }
                        // if(!item.num || !item.stand){
                        //   message.warning(请填写数量，金额)
                        //   return;
                        // }
                        item.standard_price=item.stand;
                        item.numbs = item.num;
                        item.putout_id = ticketProData[i].id;
                        param.product.push(item);
                    }
                }
                if(param.product.length==0){
                  message.warning('请点击选择出库单');
                  return false;
                }
                var val = await saveBill(param);
                if(val.errorCode==='200'){
                     message.success('提交成功')
                    actionRef.current?.reloadAndRest?.();
                    return true;
                }else{
                    message.error(val.errorMessage);
                    return  false;
                }
            }}
          >
          <ProForm.Group style={{marginLeft:'22px'}}>
              <ProFormText  name='bill_code' label='发票代码' placeholder='请输入发票' width='sm' rules={[{required: true}]}/>
              <ProFormText  name='bill_number' label='发票号码' placeholder='请输入发票号码' width='sm' rules={[{required: true}]}/>
              <ProFormDatePicker name='bill_time' label='开票日期' width='sm' rules={[{required: true}]} fieldProps={{disabledDate:disabledDate}} />
              <ProFormDigit name='amount' label='不含税总金额(产品)' placeholder='请输入金额' fieldProps={{parser:limitDecimalsP,formatter:limitDecimalsF}} width='sm'  rules={[{required: true}]}/>
          </ProForm.Group>
          <ProForm.Group style={{marginLeft:'22px'}}>
              <ProFormText  name='dealerName' readonly={true} label='销售方' placeholder='请输入销售方' rules={[{required: true}]} initialValue={sessionStorage.getItem('loginName')} width='xl'/>
              <ProFormText name='corporate_name' label='发票上开票公司名称' placeholder='请输入发票上开票公司名称' width='sm' rules={[{required: true}]}/>
              <ProFormSelect name='company_type' label='开票公司类型' placeholder='请输入开票公司类型' width='sm' rules={[{required: true}]} options={[{label:'一级客户(在直接订货的)',value:'1'},{label:'二级客户(从一级客户拿货的)',value:'2'},{label:'托管公司',value:'3'},{label:'私立医院',value:'4'},{label:'配送公司',value:'5'}]}/>
          </ProForm.Group>
          <ProForm.Group style={{marginLeft:'22px'}}>
            <ProFormSelect name='recvType' label='购买方' placeholder='请选择购买方' showSearch options={recvList} rules={[
                {
                    required: true,
                },
                ]} width='sm' fieldProps={{onSelect:onChange,filterOption:(input, option:any) =>{
                  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                }} allowClear={false}></ProFormSelect>
                <ProFormSelect hidden={hosHideFlag} name='hospital'  label='关联医院' placeholder='请选择关联医院' showSearch options={hosList} width='sm' fieldProps={{filterOption:(input, option:any) =>{
                  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                }} allowClear={true}></ProFormSelect>

              <div style={{color:'#f10000'}}>
                【购买方填写注意】<br/>
1、医院名称计入销量说明：选择发票上的医院名称上报的计入终端销量统计<br/>
2、二级商名称不计入销量说明：选择二级商公司名称的，不计入终端销量统计<br/>
                </div>
          </ProForm.Group>
          <div style={{marginLeft:'22px'}}>
            <ProFormTextArea name='bz' label='备注' placeholder='请输入备注' fieldProps={{showCount:true,maxLength:200}} />
          </div>
          <div style={{color:'red',margin:'20px 0'}}>
           如将产品销售给托管平台，上报植入需要附上产品使用证明，如：出库单、外壳包装、术中条形码等
           </div>
          <div key='tab1'>
                <Button style={{marginLeft:20}} key='chooseTicket' type='primary' onClick={()=>{
                    setChooseOut(true);
                }}>选择出库单</Button>
              {ticketProData && ticketProData.length?
              <ProTable
                style={{marginLeft:20,marginTop:20}}
                className='components-table-demo-nested'
                headerTitle='产品列表'
                size='small'
                toolbar={[]}
                columns={outColumn2}
                dataSource={ticketProData}
                rowKey='id'
                pagination={false}
                search={false}
                toolBarRender={false}
                expandable={{expandedRowRender,defaultExpandAllRows:true,expandIconColumnIndex:-1,expandedRowKeys}}
              />:<></>}

            <div style={{marginLeft:20,marginTop:20}}>
              <Upload  {...uploadProps} onPreview={handlePreview}  fileList={fileList}
              onRemove={(record)=>{
                confirm({
                  content: '确定删除吗？',
                  onOk:async()=> {
                    if(fileList.length==1){
                      message.warning('请先上传新的附件，再删除')
                      return;
                    }
                    var req = request('/xwyl/attachment/deleteAtt', {
                      method: 'POST',
                      requestType:'form',
                      data: {
                        ...{id:record.uid},
                        method: 'post',
                      },
                    });
                    var val =await req;
                    if(val.errorCode==='200'){
                      var newList=fileList.filter((item:any)=>{
                        return item.uid!=record.uid;
                      });
                      setFileList(newList);
                    }else{
                      message.error('删除失败');
                    }
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                });
              }}
                onChange={(info:any)=>{
                  if (info.file.status === 'done') {
                    if(info.file.response.errorCode==='200'){
                      var list:any[] = fileList;
                      message.success(`${info.file.name}上传成功`);
                      var data = info.file.response.data;
                      data.uid = data.attId;
                      data.name = info.file.name;
                      data.url = data.location;
                      data.status ='done';  
                      list.push(data);
                      setFileList([...list]);
                    }else{
                      message.error(`${info.file.name} 上传失败.`);
                    }
                  } else if (info.file.status === 'error') {
                    message.error(`${info.file.name} 上传失败.`);
                  }
                }}   data={{'shipId':shipId,'userId':sessionStorage.getItem('userId')}} headers={{
                  'authorization':`${sessionStorage.getItem('token')}`}}>
                <Button hidden={!props.dealer} icon={<UploadOutlined />}><span style={{color:'red'}}>*</span>上传发票</Button>
              </Upload>
            </div>
          </div>
        </DrawerForm>
      <Drawer
          destroyOnClose={true}
          width={1000}
          title={'选择出库单'}
          visible={chooseOut}
          onClose={()=>{setChooseOut(false),setPindex(0)}}
        >
        <ProTable
            headerTitle='出库单列表'
            size='small'
            toolbar={{ settings: [] }}
            columns={outColumn}
            request={(params, sorter, filter) => {
                if(params.date){
                    params.beginDate=params.date[0];
                    params.endDate=params.date[1];
                    params.date=undefined;
                }
                params.isBack=0;
                params.identification ='1'
                return putOutFormListNoBill({...params,filter})
            }}
            rowKey='id'
            pagination={{
              pageSizeOptions:['20', '100', '500']
            }}
            search={{
              span:10
            }}
          >
        </ProTable>
      </Drawer>
      <DrawerForm
            width={1300}
            title='修改发票'
            visible={editFlag}
            submitter={{
              render: (props, defaultDoms) => {
                return [
                  <span style={{color:'#f10000'}}>请再次核对上报信息是否无误，以免商务部核查有问题需再次上报！</span>,
                  ...defaultDoms,
                ];
              },
            }}
            onVisibleChange={(v)=>{
              setEditFlag(v);
            }}
            drawerProps={{
              forceRender: true,
              destroyOnClose: true,
            }}
            onFinish={async (values: any) => {
                if(fileList.length==0){
                    message.warning('请上传发票照片')
                    return false;
                }
                if(values.bill_number.length!=8){
                  message.warning('发票号码必须为8位')
                  return false;
                }
                values.shipId = shipId;
                values.customer = recv.label
                values.customerId = recv.value
                values.id=shipId
                if(values.hospital){
                  values.hospital_id=values.hospital
                }else{
                  values.hospital_id=''
                }
                var val = await updateBill(values);
                if(val.errorCode==='200'){
                     message.success('提交成功')
                    actionRef.current?.reloadAndRest?.();
                    return true;
                }else{
                    message.error(val.errorMessage);
                    return  false;
                }
            }}
          >
          <ProForm.Group style={{marginLeft:'22px'}}>
              <ProFormText  name='bill_code' label='发票代码' initialValue={currentRecord?.bill?.bill_code}  placeholder='请输入发票' width='sm' rules={[{required: true}]}/>
              <ProFormText  name='bill_number' label='发票号码' initialValue={currentRecord?.bill?.bill_number}  placeholder='请输入发票号码' width='sm' rules={[{required: true}]}/>
              <ProFormDatePicker name='bill_date' label='开票日期' initialValue={currentRecord?.bill?.bill_date}  fieldProps={{disabledDate:disabledDate}} width='sm' rules={[{required: true}]} />
              <ProFormDigit name='taxAmount' label='不含税总金额(产品)' initialValue={currentRecord?.bill?.taxAmount} placeholder='请输入金额' fieldProps={{parser:limitDecimalsP,formatter:limitDecimalsF}} width='sm'  rules={[{required: true}]}/>
          </ProForm.Group>
          <ProForm.Group style={{marginLeft:'22px'}}>
            <ProFormText  name='dealerName' readonly={true} label='销售方' placeholder='请输入销售方' rules={[{required: true}]} initialValue={sessionStorage.getItem('loginName')} width='xl'/>
              <ProFormSelect hidden={hosHideFlag} name='hospital' label='关联医院' initialValue={currentRecord?.bill?.hospital_id} placeholder='请选择关联医院' showSearch options={hosList} width='sm' fieldProps={{filterOption:(input, option:any) =>{
                return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0}
              }} allowClear={true}></ProFormSelect>

              <ProFormText name='corporate_name' label='发票上开票公司名称' placeholder='请输入发票上开票公司名称' width='sm' rules={[{required: true}]} initialValue={currentRecord?.bill?.corporate_name} />
              <ProFormSelect name='company_type' label='开票公司类型' placeholder='请输入开票公司类型' width='sm' rules={[{required: true}]} initialValue={currentRecord?.bill?.company_type}  options={[{label:'一级客户(在直接订货的)',value:'1'},{label:'二级客户(从一级客户拿货的)',value:'2'},{label:'托管公司',value:'3'},{label:'私立医院',value:'4'},{label:'配送公司',value:'5'}]}/>
          </ProForm.Group>
          <ProForm.Group style={{marginLeft:'22px'}}>
            {sessionStorage.getItem('access')?.indexOf('admin')<0? <ProFormSelect name='recvType' label='购买方' initialValue={currentRecord?.bill?.customerId} placeholder='请选择购买方' showSearch options={recvList} rules={[
                {
                    required: true,
                },
                ]} width='sm' fieldProps={{onSelect:onChange,filterOption:(input, option:any) =>{
                  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                }} allowClear={false}></ProFormSelect>: <ProFormText  name='recvType' label='购买方' initialValue={currentRecord?.bill?.customer}  readonly width='sm'/>
                }

<div style={{color:'#f10000'}}>
                【购买方填写注意】<br/>
1、医院名称计入销量说明：选择发票上的医院名称上报的计入终端销量统计<br/>
2、二级商名称不计入销量说明：选择二级商公司名称的，不计入终端销量统计<br/>
                </div>
          </ProForm.Group>
          <div style={{marginLeft:'22px'}}>
            <ProFormTextArea name='bz' label='备注' placeholder='请输入备注' initialValue={currentRecord?.bill?.bz} fieldProps={{showCount:true,maxLength:200}} />
          </div>
          <div style={{color:'red',margin:'20px 0'}}>
           如将产品销售给托管平台，上报植入需要附上产品使用证明，如：出库单、外壳包装、术中条形码等
           </div>
          <div key='tab1'>
            <div style={{marginLeft:20,marginTop:20}}>
              <Upload  {...uploadProps} onPreview={handlePreview}  fileList={fileList}
              onRemove={(record)=>{
                confirm({
                  content: '确定删除吗？',
                  onOk:async()=> {
                    if(fileList.length==1){
                      message.warning('请先上传新的附件，再删除')
                      return;
                    }
                    var req = request('/xwyl/attachment/deleteAtt', {
                      method: 'POST',
                      requestType:'form',
                      data: {
                        ...{id:record.uid},
                        method: 'post',
                      },
                    });
                    var val =await req;
                    if(val.errorCode==='200'){
                      var newList=fileList.filter((item:any)=>{
                        return item.uid!=record.uid;
                      });
                      setFileList(newList);
                    }else{
                      message.error('删除失败');
                    }
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                });
              }}
                onChange={(info:any)=>{
                  if (info.file.status === 'done') {
                    if(info.file.response.errorCode==='200'){
                      var list:any[] = fileList;
                      message.success(`${info.file.name}上传成功`);
                      var data = info.file.response.data;
                      data.uid = data.attId;
                      data.name = info.file.name;
                      data.url = data.location;
                      data.status ='done';  
                      list.push(data);
                      setFileList([...list]);
                    }else{
                      message.error(`${info.file.name} 上传失败.`);
                    }
                  } else if (info.file.status === 'error') {
                    message.error(`${info.file.name} 上传失败.`);
                  }
                }}   data={{'shipId':shipId,'userId':sessionStorage.getItem('userId')}} headers={{
                  'authorization':`${sessionStorage.getItem('token')}`}}>
                <Button hidden={!props.dealer} icon={<UploadOutlined />}><span style={{color:'red'}}>*</span>上传发票</Button>
              </Upload>
            </div>
          </div>
        </DrawerForm>
      <Spin spinning={spinningFlag} style={{transform:'translate(-50%,-50%)',left:'50%',top:'50%',position:'absolute'}}/>
  </PageContainer>
  );
}

export default DealerTicket;